package cn.likole.oj.module;


import cn.likole.oj.bean.User;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.plugins.apidoc.annotation.Api;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@IocBean
@At("/rank")
@Filters(@By(type = CheckSession.class, args = {"uid", "/"}))
@Api(name = "排名模块",description = "跟排名相关的模块")
public class RankModule {


    @Inject
    private Dao dao;


    @At
    @Api(name = "获取英雄榜",description = "参数为排名周期，为天、周、月、年")
    public List<Record> getHeroList(@Param("method")int method, @Param("page")int page){
        int pagesize=50;
        int num=(page-1)*50;
        Date date=new Date();
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(date);
        String sqlstr="SELECT user.`userId`,`nickname`,s.`solved`,t.`submit` FROM `user` " +
                "inner join (select count(distinct problemId) solved ,userId from solution " +
                "where inDate>@date and result=4 " +
                "group by userId order by solved desc limit @num,@pagesize) s " +
                "on user.userId=s.userId " +
                "inner join (select count( problemId) submit ,userId from solution " +
                "where inDate>@date " +
                "group by userId order by submit desc ) t" +
                " on user.userId=t.userId " +
                "ORDER BY s.`solved` DESC,t.submit,registerTime  LIMIT  0,50 ";
        if(method==0){
            return dao.query("user",Cnd.where("valid","=",1).desc("solved").asc("submit").asc("registerTime"), dao.createPager(page,pagesize),"userId,nickname,solved,submit");
        }else if(method==1){
            calendar.add(Calendar.DAY_OF_YEAR,-1);
        }else if(method==2){
            calendar.add(Calendar.WEEK_OF_YEAR,-1);
        }else if(method==3){
            calendar.add(Calendar.MONTH,-1);
        }else{
            calendar.add(Calendar.YEAR,-1);
        }
        Sql sql= Sqls.create(sqlstr);
        sql.params().set("date",calendar.getTime());
        sql.params().set("num",num);
        sql.params().set("pagesize",pagesize);
        sql.setCallback(Sqls.callback.records());
        sql.setEntity(dao.getEntity(Record.class));
        dao.execute(sql);
        List<Record> list=(List<Record>)sql.getResult();
        return list;

    }


    @At
    @Api(name = "获取天体榜",description = "参数为排名周期，为天、周、月、年")
    public List<User> getHeatList(){
        return null;
    }

    @At
    public void getUserProfile(){
        //todo:重定向页面
    }
}
